package com.searchengine.controller;

import com.searchengine.entity.SearchHistory;
import com.searchengine.entity.SearchResult;
import com.searchengine.entity.User;
import com.searchengine.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 搜索控制器
 */
@RestController
@RequestMapping("/api/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    /**
     * 执行搜索
     */
    @GetMapping
    public ResponseEntity<List<SearchResult>> search(
            @RequestParam String q,
            @RequestAttribute(value = "user", required = false) User user,
            @RequestHeader("X-Real-IP") String ipAddress) {
        Long userId = user != null ? user.getId() : null;
        List<SearchResult> results = searchService.search(q, userId, ipAddress);
        return ResponseEntity.ok(results);
    }

    /**
     * 获取用户搜索历史
     */
    @GetMapping("/history")
    public ResponseEntity<List<SearchHistory>> getSearchHistory(
            @RequestAttribute("user") User user,
            @RequestParam(defaultValue = "10") Integer limit) {
        List<SearchHistory> history = searchService.getUserSearchHistory(user.getId(), limit);
        return ResponseEntity.ok(history);
    }

    /**
     * 清除用户搜索历史
     */
    @DeleteMapping("/history")
    public ResponseEntity<Void> clearSearchHistory(@RequestAttribute("user") User user) {
        searchService.clearUserSearchHistory(user.getId());
        return ResponseEntity.noContent().build();
    }

    /**
     * 使用AI增强搜索
     */
    @PostMapping("/ai-enhance")
    public ResponseEntity<List<SearchResult>> enhanceWithAI(
            @RequestBody Map<String, Object> requestData,
            @RequestAttribute(value = "user", required = false) User user,
            @RequestHeader("X-Real-IP") String ipAddress) {
        String query = (String) requestData.get("query");
        Long userId = user != null ? user.getId() : null;
        
        // 先执行普通搜索
        List<SearchResult> results = searchService.search(query, userId, ipAddress);
        
        // 再使用AI增强结果
        List<SearchResult> enhancedResults = searchService.enhanceWithAI(results, query);
        
        return ResponseEntity.ok(enhancedResults);
    }
}